import random
from aiohttp import web
from typing import Dict, Any

# 递归转换 set 为 list
def convert_set_to_list(obj):
    if isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        return {k: convert_set_to_list(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_set_to_list(i) for i in obj]
    else:
        return obj

# 内存用户字典和ID计数器
users: Dict[str, Dict[str, Any]] = {}
user_id_counter = 0

def generate_user_info():
    adjectives = ['快乐的', '聪明的', '友好的', '活泼的', '可爱的', '机智的', '温暖的', '有趣的']
    nouns = ['小猫', '小狗', '小鸟', '小兔', '小鹿', '小象', '小虎', '小狮']
    adjective = random.choice(adjectives)
    noun = random.choice(nouns)
    number = random.randint(0, 999)
    username = f"{adjective}{noun}{number}"
    colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F']
    avatar_color = random.choice(colors)
    return {
        'username': username,
        'avatar_color': avatar_color,
        'avatar_text': username[:2]
    }

async def register(request):
    global user_id_counter
    data = await request.json()
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return web.json_response({'success': False, 'msg': '用户名和密码不能为空'}, status=400)
    if username in users:
        return web.json_response({'success': False, 'msg': '用户名已存在'}, status=400)
    user_id_counter += 1
    user_info = generate_user_info()
    users[username] = {
        'id': user_id_counter,
        'username': username,
        'password': password,
        'avatar_color': user_info['avatar_color'],
        'avatar_text': user_info['avatar_text'],
        'friends': set()
    }
    return web.json_response({'success': True, 'msg': '注册成功'})

async def login(request):
    data = await request.json()
    username = data.get('username')
    password = data.get('password')
    user = users.get(username)
    if not user or user['password'] != password:
        return web.json_response({'success': False, 'msg': '用户名或密码错误'}, status=400)
    user_info = {k: v for k, v in user.items() if k != 'password'}
    resp = {'success': True, 'msg': '登录成功', 'user': user_info}
    return web.json_response(convert_set_to_list(resp))
